import { createRouter, createWebHistory,createWebHashHistory} from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import Layout from '@/layout/Layout.vue'
import {useMenuStore} from '@/store/settings'

// 路由按模块分类
import common from './common'

const menuStaic = [
    {
        path: '/',
        chineseName: '基本信息',
        component: Layout,
        type: 1,
        icon: 'Menu',
        children:[
            {
                path: '/about',
                name: 'About',
                chineseName: '使用手册',
                component: () => import('@/views/About.vue'),
                type: 1,
                icon: 'HelpFilled',
                meta: { title: '使用手册' },
            },
            {
                path: '/faceJob',
                name: 'face',
                chineseName: '开始换脸',
                component: () => import('@/views/system/Facejob.vue'),
                type: 1,
                icon: 'Pointer',
                meta: { title: '开始换脸' },
            }
        ]
    }

]

// createRouter 创建路由实例
const router = createRouter({
    /**
     * hash模式：createWebHashHistory，
     * history模式：createWebHistory
     */
    history: createWebHashHistory(),
    routes:[
        ...common,
        ...menuStaic
    ]
})

NProgress.inc(0.2)
NProgress.configure({ easing: 'ease', speed: 600, showSpinner: false })

let flag = true // 刷新标识
router.beforeEach(async (to, from, next) => {
    // 启动进度条
    NProgress.start()

    // 是否登陆
    if (!sessionStorage.getItem('token') && (to.path !== "/login" && to.path !== "/register")) {
        return next({ path: "/login" });
    };

    // 设置头部
    if (to.meta.title) {
        document.title = to.meta.title
    } else {
        document.title = "mydeepface"
    }


    if(sessionStorage.getItem('token') && flag){
        const menuStore = useMenuStore();
        menuStore.setMenu([...menuStaic]);
        flag = false
        next({ ...to, replace: true })
    }else{
        next()
    }
})

router.afterEach(() => {
    // 关闭进度条
    NProgress.done()
})

export default router
